//
//  YZMAddBankCardViewController.m
//  YZMicroStock
//
//  Created by Lv.Dongdong on 16/7/12.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMAddBankCardViewController.h"
#import "YZMProvince.h"
#import "YZMCity.h"
#import "YZMSeparatorCell.h"
#import "YZClient.h"
#import "MBProgressHUD+Utils.h"
#import "YZMProvinceListViewController.h"
#import "YZMBranchListViewController.h"
#import <BlocksKit/UIControl+BlocksKit.h>
#import "YZMAddBankCardCell.h"
#import "YZMBankModel.h"
#import "YZMBankCardService.h"
#import "YZClient+BankCard.h"
#import "YZMAlertView.h"

#define ADD_BANK_CARD_TAG_FOR_USERNAME  1000
#define ADD_BANK_CARD_TAG_FOR_BANKNAME              ADD_BANK_CARD_TAG_FOR_USERNAME + 1
#define ADD_BANK_CARD_TAG_FOR_PROCINCE              ADD_BANK_CARD_TAG_FOR_BANKNAME + 1
#define ADD_BANK_CARD_TAG_FOR_BRANCH                ADD_BANK_CARD_TAG_FOR_PROCINCE + 1
#define ADD_BANK_CARD_TAG_FOR_BANKNUM               ADD_BANK_CARD_TAG_FOR_BRANCH + 1
#define ADD_BANK_CARD_TAG_FOR_BANKNUM_COMFIRM       ADD_BANK_CARD_TAG_FOR_BANKNUM + 1

static NSString *const sYZMAddBankCardCellID = @"YZMAddBankCardID";

@interface YZMAddBankCardViewController() <UITableViewDelegate, UITableViewDataSource, YZMLocationChooseDelegate, YZMBranchChooseDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) YZMProvince *province;
@property (nonatomic, strong) YZMCity *city;
@property (nonatomic, strong) NSString *branch;
@property (nonatomic, strong) UIButton *submitBT;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) YZMBankModel *bankModel;
@property (nonatomic, strong) UITextField *bankNumberTF;
@property (nonatomic, strong) UITextField *bankNumComfirmTF;
@property (nonatomic, strong) NSString *bankNumberStr;
@property (nonatomic, strong) NSString *bankNumComfirmStr;

@property (nonatomic, strong) NSDictionary *params;

@end

@implementation YZMAddBankCardViewController

- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = @[@[@[@"开户名", @(ADD_BANK_CARD_TAG_FOR_USERNAME)],
                          @[@"开户银行", @(ADD_BANK_CARD_TAG_FOR_BANKNAME)],
                          @[@"开户省市", @(ADD_BANK_CARD_TAG_FOR_PROCINCE)],
                          @[@"开户支行", @(ADD_BANK_CARD_TAG_FOR_BRANCH)]],
                        
                        @[@[@"银行卡号", @(ADD_BANK_CARD_TAG_FOR_BANKNUM)],
                          @[@"确认卡号", @(ADD_BANK_CARD_TAG_FOR_BANKNUM_COMFIRM)]]];
    }
    return _dataSource;
}

- (void)viewDidLoad{
    
    [super viewDidLoad];
    self.title = @"添加银行卡";
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    [self createObjects];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyboard:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark -- KeyboardNotification
- (void)showKeyboard:(NSNotification *)noti {
    NSDictionary *dic = noti.userInfo;
    //键盘弹出后的位置
    CGRect endFrame = [dic[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make){
        make.bottom.equalTo(self.view).offset(-endFrame.size.height);
    }];
}

- (void)hideKeyboard:(NSNotification *)noti {
    
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make){
        make.bottom.equalTo(self.view);
    }];
}

#pragma mark -- network

- (void)submitBankCardDetailModify{
    [self resignAllFirstResponder];
    
    NSString *bankCard = [self.bankNumberStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (bankCard.length < 15 || bankCard.length > 21) {
        
        [MBProgressHUD showMessage:@"银行卡号不符合规范"];
        return;
    }
    
    if (![self.bankNumberStr isEqualToString:self.bankNumComfirmStr]) {
        
        [MBProgressHUD showMessage: @"两次卡号输入不一致"];
        return;
    }
    
    [YZClient bc_addBankCardWithBankName:self.bankModel.name andProvince:self.province.name andCity:self.city.name andBranch:self.branch andCardNumber:self.bankNumberStr success:^(NSURLResponse *response, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            [MBProgressHUD showMessage: @"银行卡添加成功"];
             [YZMUserServiceInstance fetchUserBankCardInfo];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //检测提现密码是否设置
                if (!YZMUserServiceInstance.user.detail.isWithDrawPw) {
//
//                    YZMAlertView *view = [YZMAlertView alertViewForRecommandWithContent:@"还未设置提现密码"];
//                    [view.sureButton setTitle:@"设定" forState:UIControlStateNormal];
//                    view.confirmHandle = ^(){
                        [YZMHCMInstance pushViewControllerWithName:@"setWdPwd" andParams:self.params];
                        return;
                   }
//
//                    view.cancelButton.hidden = NO;
//                    view.cancleHandle = ^(){
//
//
//                    };
//                    [view showInView:self.navigationController.view];
//                    return;
//                }
                 [YZMHCMInstance popViewController];
            });
            
        }else{
            
            [topModel showMessage];
        }
        
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

#pragma mark -- delegate

- (void)provinceDidChoose:(YZMProvince *)province andCity:(YZMCity *)city{
    
    if (self.city) {
        
        if (![self.city.name isEqualToString:city.name]) {
            
            self.branch = nil;
        }
    }
    
    self.province = province;
    self.city = city;
    [self.tableView reloadData];
    self.submitBT.enabled = NO;
}

- (void)branchDidChoose:(NSString *)branch{
    
    self.branch = branch;
    [self.tableView reloadData];
    
    [self textValueChanged];
}

#pragma mark -- ui

- (void)createObjects{
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.backgroundColor = [YZMAppStyle appBackgroundColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView registerClass:[YZMAddBankCardCell class] forCellReuseIdentifier:sYZMAddBankCardCellID];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make){
        
        make.top.equalTo(self.view);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    NSString *name = YZMUserServiceInstance.user.detail.name;
    if (name.length > 0) {
        
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
        
        NSString *text = [NSString stringWithFormat:@"为确保资金安全，只能添加“%@”的银行卡", [name formatName]];
        UILabel *label = [YZMAppStyle labelWithFont:[YZMAppStyle smallSizeFont] andColor:[YZMAppStyle colorForYellowButton]];
        label.numberOfLines = 0;
        label.text = text;
        label.textAlignment = NSTextAlignmentCenter;
        
        [headerView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(headerView).offset(15);
            make.right.equalTo(headerView).offset(-15);
            make.top.equalTo(headerView).offset(20);
        }];
        self.tableView.tableHeaderView = headerView;
    }

    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 84)];
    self.submitBT = [YZMAppStyle NewsubmitButton];
    [self.submitBT setTitle:@"确定" forState:UIControlStateNormal];
    [self.submitBT bk_addEventHandler:^(id sender) {
        [self submitBankCardDetailModify];
        
    } forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:self.submitBT];
    [self.submitBT mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(footerView);
        make.left.equalTo(footerView).offset(15);
        make.right.equalTo(footerView).offset(-15);
    }];
    self.tableView.tableFooterView = footerView;
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMAddBankCardViewController *addBankVc = [[YZMAddBankCardViewController alloc] init];
    [addBankVc updateParams:params];
    return addBankVc;
}
- (void)updateParams:(NSDictionary *)params{
    self.params = params;
}

#pragma mark -- Textfield

- (void)textValueChanged {
    
    if (self.bankNumberStr.length == 0 || self.bankNumComfirmStr.length == 0) {
        
        self.submitBT.layer.borderWidth=1.0;
        self.submitBT.enabled = NO;
        return;
    }
    
    if (!self.province || !self.city || !self.branch) {
        
        self.submitBT.layer.borderWidth=1.0;
        self.submitBT.enabled = NO;
        return;
    }
    
    self.submitBT.layer.borderWidth=0;
    self.submitBT.enabled = YES;
}

- (void)resignAllFirstResponder {
    
    [self.bankNumberTF resignFirstResponder];
    [self.bankNumComfirmTF resignFirstResponder];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}

#pragma mark -- UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YZMAddBankCardCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMAddBankCardCellID];
//    cell.backgroundColor = [UIColor whiteColor];
    cell.textLabel.textColor = [YZMAppStyle colorForMainTextColor];
    cell.textLabel.font = [YZMAppStyle mediumSizeFont];
    cell.rightMargin = 0.0;
    cell.placeholderLB.textColor = [YZMAppStyle colorForGrayText];
    [cell showContentcontroller:YES];
    
    NSArray *tempArray = self.dataSource[indexPath.section][indexPath.row];
    NSInteger tag = [tempArray[1] integerValue];
    WS(ws)
    switch (tag) {
        case ADD_BANK_CARD_TAG_FOR_USERNAME:{
            
            cell.accessoryView = [[UIImageView alloc] init];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.text = tempArray[0];
            NSString *name = YZMUserServiceInstance.user.detail.name;
            if (name.length > 0) {
                
                cell.placeholderLB.text = [name formatName];
                cell.placeholderLB.textColor = [YZMAppStyle colorForMainTextColor];
            }
        }
            break;
        case ADD_BANK_CARD_TAG_FOR_BANKNAME:{
            
            cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left_arrow"]];
            cell.textLabel.text = tempArray[0];
            
            if (!self.bankModel) {
                
                cell.placeholderLB.text = @"请选择银行";
            } else {
                
                cell.placeholderLB.text = self.bankModel.name;
                cell.placeholderLB.textColor = [YZMAppStyle colorForMainTextColor];
            }
        }
            break;
        case ADD_BANK_CARD_TAG_FOR_PROCINCE:{
            
            cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left_arrow"]];
            cell.textLabel.text = tempArray[0];
            if (!self.province && !self.city) {
                
                cell.placeholderLB.text = @"请选择省市";
            }else{

                cell.placeholderLB.text = [self.province.name stringByAppendingFormat:@" %@",self.city.name];
                cell.placeholderLB.textColor = [YZMAppStyle colorForMainTextColor];
            }
        }
            break;
        case ADD_BANK_CARD_TAG_FOR_BRANCH:{
            
            cell.textLabel.text = tempArray[0];
            cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left_arrow"]];
            if (!self.branch) {
                
                cell.placeholderLB.text = @"请选择所属支行";
                
            }else{
 
                cell.placeholderLB.text = self.branch;
                cell.placeholderLB.textColor = [YZMAppStyle colorForMainTextColor];
            }
        }
            break;
        case ADD_BANK_CARD_TAG_FOR_BANKNUM:{
            
            cell.accessoryView = [[UIImageView alloc] init];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.text = tempArray[0];
            cell.bankNumTF.placeholder = @"请输入银行卡号";
            if (self.bankNumberStr) {
                
                cell.bankNumTF.text = self.bankNumberStr;
            }
            self.bankNumberTF = cell.bankNumTF;
            [cell showContentcontroller:NO];
            cell.selectAction = ^(UITextField *send) {
                
                ws.bankNumberStr = send.text;
                [ws textValueChanged];
            };
        }
            break;
        case ADD_BANK_CARD_TAG_FOR_BANKNUM_COMFIRM:{
            
            cell.accessoryView = [[UIImageView alloc] init];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.text = tempArray[0];
            cell.bankNumTF.placeholder = @"确认银行卡号";
            if (self.bankNumComfirmStr) {
                
                cell.bankNumTF.text = self.bankNumComfirmStr;
            }
            self.bankNumComfirmTF = cell.bankNumTF;
            [cell showContentcontroller:NO];
            cell.selectAction = ^(UITextField *send) {
                
                ws.bankNumComfirmStr = send.text;
                [ws textValueChanged];
            };
        }
            break;
        default:
            break;
    }
    
    [cell.contentView insertSubview:cell.textLabel belowSubview:cell.bottomLineView];
    YZMIndexCount indexCount;
    indexCount.index = indexPath.row;
    indexCount.count = [self.dataSource[indexPath.section] count];
    cell.indexCount = indexCount;
    
    return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.dataSource[section] count];
}

#pragma mark -- UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return [[UIView alloc] init];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    NSArray *tempArray = self.dataSource[indexPath.section][indexPath.row];
    NSInteger tag = [tempArray[1] integerValue];
    
    switch (tag) {
        case ADD_BANK_CARD_TAG_FOR_BANKNAME: {
            
            WS(ws)
            [YZMHCMInstance pushViewControllerWithName:@"YZMBankListViewController" andParams:@{@"selectAction":^(YZMBankModel *bank){
                
                if (ws.bankModel) {
                    
                    if (![ws.bankModel.name isEqualToString:bank.name]) {
                        
                        ws.branch = nil;
                    }
                }
                ws.bankModel = bank;
                [tableView reloadData];
                ws.submitBT.enabled = NO;
            }}];
             
        }
            break;
            
        case ADD_BANK_CARD_TAG_FOR_PROCINCE:
            
            [YZMHCMInstance pushViewControllerWithName:@"provinceList" andParams:@{@"delegate":self}];
            break;
        case ADD_BANK_CARD_TAG_FOR_BRANCH: {
            
            if (!(self.province && self.city && self.bankModel)) {
                
                [MBProgressHUD showMessage:@"请先选择开户银行以及所在省市"];
                return;
            }
            
            MBProgressHUD *hud = [MBProgressHUD showMessageManual:@"获取支行信息中"];
            
            
            [YZClient bc_fetchBranchListWithBankName:self.bankModel.name andProvince:self.province.name andCity:self.city.name success:^(NSURLResponse *response, id responseObject) {
                
                [hud hide:NO];
                YZGeneralResultModel *topModel = responseObject;
                if (topModel.success) {
                    
                    [YZMHCMInstance pushViewControllerWithName:@"branchList" andParams:@{@"delegate":self,@"branchList":topModel.data}];
                }else{
                    
                    [topModel showMessage];
                }
            } failure:^(NSError *error) {
                
                [hud hide:NO];
                [error yz_showMessage];
            }];
        }
            break;
        default:
            break;
    }
}

@end
